package com.chen.controller;


import com.chen.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.reggiepath}")
    private String reggiepath;


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        //生成一个文件名
        String name = UUID.randomUUID().toString();
        //准备文件夹
        File file1 = new File(reggiepath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            //将临时文件转存到指定文件夹下
            file.transferTo(new File(reggiepath + name));
        } catch (IOException e) {
            return R.error("文件上传失败");
        }
        return R.success(name);
    }

    /**
     * 文件回显
     *
     * @param response
     * @param name
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) throws IOException {
        //使用输入流对象,关联指定文件
        FileInputStream fis = new FileInputStream(new File(reggiepath, name));
        //
        log.info(name);
        ServletOutputStream sos = response.getOutputStream();
        response.setContentType("imge/jpge");
        IOUtils.copy(fis, sos);
        fis.close();
    }

    public void deleteimg(String name) {
        new File(reggiepath + name).delete();
    }
}
